import { createRouter, createWebHistory } from 'vue-router'
import { message } from 'ant-design-vue'
import HomeView from '@/pages/HomePage.vue'
import { useLoginUserStore } from '@/stores/loginUser'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
  {
    path: '/',
    name: 'home',
    component: HomeView,
  },
  {
    path: '/explore',
    name: 'explore',
    component: () => import('@/pages/ExplorePage.vue'),
  },
  {
    path: '/docs',
    name: 'docs',
    component: () => import('@/pages/DocsPage.vue'),
  },
  {
    path: '/app/chat/:appId',
    name: 'appChat',
    component: () => import('@/pages/AppChatPage.vue'),
    meta: {
      requiresAuth: true,
    },
  },
  {
    path: '/admin/app-manager',
    name: 'appManager',
    component: () => import('@/pages/admin/AppManager.vue'),
    meta: {
      requiresAuth: true,
      requiresAdmin: true,
    },
  },
  {
    path: '/app/edit/:appId',
    name: 'appEdit',
    component: () => import('@/pages/AppEditPage.vue'),
    meta: {
      requiresAuth: true,
    },
  },
  {
    path: '/app/detail/:appId',
    name: 'appDetail',
    component: () => import('@/pages/AppDetailPage.vue'),
    meta: {
      requiresAuth: true,
    },
  },

  {
    path: '/user/edit',
    name: 'userEdit',
    component: () => import('@/pages/user/EditUser.vue'),
    meta: {
      requiresAuth: true,
    },
  },
  {
    path: '/admin/user-manager',
    name: 'userManager',
    component: () => import('@/pages/admin/UserManager.vue'),
    meta: {
      requiresAuth: true,
      requiresAdmin: true,
    },
  },
  {
    path: '/admin/chat-history-manager',
    name: 'chatHistoryManager',
    component: () => import('@/pages/admin/ChatHistoryManager.vue'),
    meta: {
      requiresAuth: true,
      requiresAdmin: true,
    },
  },
  {
    path: '/user/login',
    name: 'UserLogin',
    component: () => import('@/pages/user/UserLogin.vue'),
    meta: {
      hideInMenu: true,
    },
  },
  {
    path: '/user/register',
    name: 'UserRegister',
    component: () => import('@/pages/user/UserRegister.vue'),
    meta: {
      hideInMenu: true,
    },
  },
  ],
})

// 是否为首次获取登录用户
let firstFetchLoginUser = true

// 全局路由守卫
router.beforeEach(async (to, from, next) => {
  const loginUserStore = useLoginUserStore()
  let loginUser = loginUserStore.loginUser

  // 确保页面刷新，首次加载时，能够等后端返回用户信息后再校验权限
  if (firstFetchLoginUser) {
    await loginUserStore.fetchLoginUser()
    loginUser = loginUserStore.loginUser
    firstFetchLoginUser = false
  }

  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    if (!loginUser || !loginUser.id) {
      message.warning('请先登录')
      next(`/user/login?redirect=${to.fullPath}`)
      return
    }
  }

  // 检查是否需要管理员权限
  if (to.meta.requiresAdmin) {
    if (!loginUser || loginUser.userRole !== 'admin') {
      message.error('没有权限')
      next(`/user/login?redirect=${to.fullPath}`)
      return
    }
  }

  // 检查管理员路径
  if (to.path.startsWith('/admin')) {
    if (!loginUser || loginUser.userRole !== 'admin') {
      message.error('没有权限')
      next(`/user/login?redirect=${to.fullPath}`)
      return
    }
  }

  next()
})

export default router
